package com.pokeoffice.logs;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * The Class Log.
 */
public class Log {

	/** The APPT. */
	public static LogType APPT = LogType.APPOINTMENT;
	
	/** The AUTH. */
	public static LogType AUTH = LogType.AUTHORIZATION;
	
	/** The ERR. */
	public static LogType ERR = LogType.ERROR;
	
	/** The SERV. */
	public static LogType SERV = LogType.SERVER;
	
	/** The TEST. */
	public static LogType TEST = LogType.TEST;
	
	/** The USER. */
	public static LogType USER = LogType.USER;

	/** The Constant APPEND. */
	private static final boolean APPEND = true;

	/**
	 * Based on the type of log provided, the method switches to the correct log
	 * file and writes to the end of the log.
	 *
	 * @param w the w
	 * @param s the s
	 */
	public static void write(LogType w, String s) {
		switch (w) {
		case APPOINTMENT: // Appointment creation and modification
			write(new File("files/logs/appointments.log"), s);
			break;
		case AUTHORIZATION: // user logins, authorization checks
			write(new File("files/logs/authorization.log"), s);
			break;
		case ERROR: // errors in the application
			write(new File("files/logs/error.log"), s);
			break;
		case SERVER: // server startup, errors
			write(new File("files/logs/server.log"), s);
			break;
		case TEST: // errors in the application
			write(new File("files/logs/test.log"), s);
			break;
		case USER: // new users and changes made to users
			write(new File("files/logs/users.log"), s);
			break;
		default:
			String output = "Bad Write Type: " + w.toString();
			System.out.println(output);
			write(new File("files/logs/error.log"), output);
			break;
		}
	}

	/**
	 * Write.
	 *
	 * @param f the f
	 * @param s the s
	 */
	private static void write(File f, String s) {
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter(f, APPEND));
			String dateFormat = "yyyy:MM:dd::HH:mm:ss";
			Calendar cal = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

			String time = sdf.format(cal.getTime());
			String logEntry = "[" + time + "] " + s;

			out.write(logEntry);
			out.newLine();
			out.flush();
			out.close();
		} catch (IOException e) {
			Log.write(LogType.ERROR, "Error Writing to Log");
		}
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		return "This class Logs actions performed";
	}

	/**
	 * The Enum LogType.
	 *
	 * @author   kyle
	 */
	private enum LogType {
		
		/** The APPOINTMENT. */
		APPOINTMENT, 
		
		/** The AUTHORIZATION. */
		AUTHORIZATION, 
		
		/** The ERROR. */
		ERROR, 
		
		/** The SERVER. */
		SERVER, 
		
		/** The TEST. */
		TEST, 
		
		/** The USER. */
		USER;
	}

}
